iT邦幫忙

2025 iThome 鐵人賽

DAY 9
0
事情總是事與願違... 還以為今天可以開始動工了。 

IAM Identity Center 的使用者與權限都已經就緒,接下來進入實戰環節!

在本地開發環境裡,讓 VS Code 透過 AWS Toolkit 連上剛才設定好的 IAM Identity Center 帳號,並從 S3 讀取資料。

要讀檔首先要有檔案

  • 使用系統管理者[^1]: 登入 Console,進入 S3 頁面
    https://ithelp.ithome.com.tw/upload/images/20250923/2016843774A15cYf93.png
  • 按下「建立儲存貯體」
    https://ithelp.ithome.com.tw/upload/images/20250923/201684379KPR5PP7Xo.png
  • 特別留意,S3 Bucket 的名稱必須是 全域命名空間中為唯一
    https://ithelp.ithome.com.tw/upload/images/20250923/20168437wA0d2OSyfh.png

全域命名空間中唯一

官方文件是這麼說的:

Bucket names must be unique across all AWS accounts in all of the AWS Regions within a partition. A partition is a grouping of Regions. AWS currently has three partitions: aws (commercial Regions), aws-cn (China Regions), and aws-us-gov (AWS GovCloud (US) Regions)

AWS 分為三個 Partition:商業用的一般 AWS 區域、中國專用區域、美國政府專用區域,這裡取的 bucket 名稱必須是在 Partition 中唯一。
簡單說,一般使用到的這些 Region (雪梨、東京、新加坡...) 皆同屬 commercial partition,Bucket Name 是不允許重複的。

  • 建立好之後上傳一個測試用檔案
    https://ithelp.ithome.com.tw/upload/images/20250923/20168437vQRJRTwy0C.png

從 VS Code 建立與 AWS 的連線

  • 首先打開一個乾淨的的 VS Code 視窗,點開左邊列表中的 AWS Toolkit
    https://ithelp.ithome.com.tw/upload/images/20250923/201684372hLOZNE1Aq.png
  • 點選 Select a Connection,然後選擇 Add New Connection
    https://ithelp.ithome.com.tw/upload/images/20250923/20168437pfIEjYeDXx.png
  • 出現兩個選項:WorkforceIAM Credentials
    https://ithelp.ithome.com.tw/upload/images/20250923/2016843751FjXQYfC4.png

之所以要設定那麼久的 IAM Identity Center 就是為了這一步啊!

如果選擇 IAM Credentials,接下來就會需要提供 Access KeySecret Key。但先前明明才提過:非必要請不要建立 IAM 金鑰。
既然都已經設定好 IAM Identity Center,就可以安心選擇 Workforce,然後選擇 Continue

  • 第一行就開宗明義:Sign in with AWS IAM Identity Center
    https://ithelp.ithome.com.tw/upload/images/20250923/201684379x6psXDR1J.png

不過,上面說的Start URL 是什麼?

  • 快從信箱撈撈之前收到的驗證信
    https://ithelp.ithome.com.tw/upload/images/20250923/20168437WHh3nZqDB8.png
    上面的Your AWS access portal URL 就是囉!
  • 下方要填入 IAM Identity Center 所在的 Region
    就說不要建錯地方,不然這種設定真的很容易錯啊!
    https://ithelp.ithome.com.tw/upload/images/20250923/20168437nP7OLXWEF1.png
  • 在瀏覽器上完成登入
    https://ithelp.ithome.com.tw/upload/images/20250923/20168437yRbExwOJh1.png
  • 完成登入後會出現授權許可確認,大膽地按下「允許存取」
    https://ithelp.ithome.com.tw/upload/images/20250923/20168437FnxlqwnjYX.png
  • 出現這個畫面就授權完成囉!
    https://ithelp.ithome.com.tw/upload/images/20250923/20168437BPQvaN0DVr.png
不知道是什麼原因,測試過程中偶爾會出現從瀏覽器登入後是跳轉到帳戶入口網站的情況。
但只要在 VS Code 上取消,再按一次 Continue 就會正常顯示 IDE 授權詢問了。
  • 回到 VS Code 上,就會出現剛才建立好的選項,直接點它!
    https://ithelp.ithome.com.tw/upload/images/20250923/20168437EW8CMHIRiD.png
  • 畫面中央會出現 IAM Identity Center 的選項,點下後會出現前幾篇建立好的 Permission Sets[^2]
    https://ithelp.ithome.com.tw/upload/images/20250923/20168437d39AJhTPMN.png
  • 畫面上出現 AWS Region 資訊就是成功連線啦!
    https://ithelp.ithome.com.tw/upload/images/20250923/20168437MqLPyB3FHf.png
  • 如果畫面上的 Region 不是實際使用的那一個,可以直接在 Region 上右鍵,就會出現設定項目
    https://ithelp.ithome.com.tw/upload/images/20250923/20168437BV4wBFZ9NN.png
  • 最後來點點看是不是真的能讀到 S3 上的檔案吧
    https://ithelp.ithome.com.tw/upload/images/20250923/20168437AjB1QJgocr.png

測試成功~!


Toolkit 成功登入代表 VS Code 可以拿到 Identity Center 發下來的 臨時憑證。
但臨時憑證到底能不能用在開發上呢...?

這種時候當然就是寫一段 code 測試!


程式使用 AWS 憑證

  • 簡單建立一個 main.py
    https://ithelp.ithome.com.tw/upload/images/20250923/20168437vG3G9LTCGa.png
  • 引入調用 AWS 服務時需要的套件:boto3
    Source Code:
    import boto3
    
    def read_s3_file(bucket_name: str, object_key: str, encoding: str = "utf-8") -> str:
        """
        讀取 AWS S3 上的檔案並回傳內容
        :param bucket_name: S3 bucket 名稱
        :param object_key: 檔案路徑
        :param encoding: 文字編碼,預設 utf-8
        :return: 檔案內容(字串)
        """
        s3_client = boto3.client("s3")
        try:
            response = s3_client.get_object(Bucket=bucket_name, Key=object_key)
            content = response["Body"].read().decode(encoding)
            return content
        except Exception as e:
            print(f"讀取 S3 檔案時發生錯誤: {e}")
            return ""
    
    # 範例使用
    if __name__ == "__main__":
        bucket = "ithome-ironman-2025"
        key = "tarot.json"
        content = read_s3_file(bucket, key)
        print(content)
    

執行!

PS C:\Projects\2025-ironman\s3-reader> python .\main.py
讀取 S3 檔案時發生錯誤: Unable to locate credentials

......欸?

原來 AWS Toolkit 取得的憑證,沒辦法直接讓 boto3 使用啊...
查閱了官方文件:boto3 1.40.35 documentation - Credentials

boto3 的驗證方式依序為:程式碼 → 環境 → 檔案 → 容器/EC2。

(詳細內容補充在文章末)

雖說 boto3 會自動抓取驗證資訊,但 Toolkit 登入後,是將暫時性憑證存在自己的快取,並利用這個驗證讓 IDE 直接操作 AWS 雲端環境,並不會寫進 boto3 使用的設定檔中。

既然 boto3 不能直接使用 Toolkit 的憑證,那只好另外設定其他適合的驗證方式。
從目前的資訊可以得知,最簡便的方式就是直接下載 AWS ACCESS KEY 並設定在環境變數,可是...這有違這個學習過程想實踐的 Best Practice。

Toolkit 的暫時性憑證不能用嗎?

且不說官方沒有提供直接取得憑證的方式,就算從設定檔把憑證找出來了,也會因為 Permission Set 設定的 工作階段持續時間 ,到期就直接失效。
還是採用正規的方式,老實設定 boto3 適用的驗證方法比較好!

就定位上來說:
Toolkit = 讓 IDE 直接操作 AWS 的入口
CLI/SSO = 讓 SDK/程式碼取得憑證的入口 ← boto3 屬於這裡

所以下一篇:boto3 的本地端驗證 但我可能還是會取一些怪標題


資訊補充

  • boto3 尋找驗證資訊的順序(由上到下,找到驗證資訊就不會繼續往下執行)
    1. 程式碼裡直接指定
      boto3.client("s3", aws_access_key_id=..., aws_secret_access_key=...)
    2. 建立 Session 時傳入
      boto3.Session(aws_access_key_id=..., aws_secret_access_key=...)
    3. 環境變數
      • AWS_ACCESS_KEY_ID
      • AWS_SECRET_ACCESS_KEY
      • AWS_SESSION_TOKEN
    4. Assume Role(透過 STS 切角色)
    5. Assume Role with Web Identity(例如 OIDC token, EKS IRSA)
    6. IAM Identity Center (SSO) Provider
      • 使用 aws configure sso → aws sso login
      • boto3 自動讀取 ~/.aws/config 與 ~/.aws/sso/cache
    7. Shared credentials file
      ~/.aws/credentials
    8. AWS config file
      ~/.aws/config
    9. 舊版 boto2 設定檔
      /etc/boto.cfg, ~/.boto
    10. Container credentials
      • ECS / EKS 中,從容器環境自動抓取
      • EC2 Instance Metadata Service (IMDS)
        如果程式在 EC2 上執行,會自動從 instance role 取得臨時憑證

[^1]: 建立系統管理員可參考文章:Day 4. 沒有人會 24 小時都是員工
[^2]: 建立 Permission Sets 可參考文章:Day 7. Identity Center:Final Season


上一篇
Day 8. 人家都說魔鬼藏在細節裡
系列文
科學的盡頭是玄學?AI占卜小助手與知識庫驗證9
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言